// pages/scoreMall/scoreMall/scoreMall.js
const productService = require('../../../api/productService.js')
const bannerService = require('../../../api/bannerService.js')
const memberService = require('../../../api/memberService.js')
const util = require('../../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentStoreInfo: {
      storeId: '',
      storeName: '未获取到门店信息'
    },
    banners: [],
    goodsList: [],
    score: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.storeInfo) {
      this.setData({
        currentStoreInfo: {
          storeId: app.globalData.storeInfo.id,
          storeName: app.globalData.storeInfo.name
        }
      })
      this.getScoreProduct(this.data.currentStoreInfo.storeId)
      this.getMemberScore()
      this.getBanners()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 获取banner图资源
   */
  getBanners: function () {
    bannerService.getBannerList('SCOREMALL').then(res => {
      this.setData({
        banners: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },


  /**
   * 获取积分商城商品
   */
  getScoreProduct: function (storeId) {
    const that = this
    let page = 1
    let pageSize = 0
    let business = 'SCORE'
    productService.query(1, 0, storeId, business).then(res => {
      console.log(res)
      if (res.records && res.records.length > 0) {
        let tempList = []
        res.records.forEach(item => {
          let produtlabel = []
          let promotions = []
          if (item.labels && item.labels.length > 0) {
            item.labels.forEach(ele => {
              if (ele.type === 'GOODSLABEL') {
                produtlabel.push(ele)
              } else if (ele.type === 'PROMOTIONLABEL') {
                promotions.push(ele)
              }
            })
          }
          let tempItem = {
            ...item,
            produtlabel: produtlabel,
            promotions: promotions
          }
          tempList.push(tempItem)
        })
        let newTempList = that.productsSort(tempList)
        that.setData({
          goodsList: newTempList
        })
      }
    })
  },
  /**
   * 商品排序
   */
  productsSort: function (array) {
    let balanceArray = []
    let allArray = []
    array.forEach(ele => {
      if (ele.balance === 0) {
        balanceArray.push(ele)
      } else {
        allArray.push(ele)
      }
    });
    const tempArray = allArray.concat(balanceArray)
    return tempArray
  },
  /**
   * 获取个人积分数据
   */
  getMemberScore: function () {
    const that = this
    if (app.globalData.userInfo.member) {
      this.setData({
        member: app.globalData.userInfo.member,
        isMember: true
      })
      memberService.getBalance(that.data.member.mobile).then(res => {
        console.log(res)
        that.setData({
          score: res
        })
      }).catch(e => {
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else {

    }
  },
  /**
   * 跳转到门店选择页
   */
  toSelectStore: function () {
    wx.navigateTo({
      url: '../../selectStore/selectStore',
    })
  },
  /**
   * 跳转到积分商城订单页面
   */
  toScoreOrder: function () {
    wx.navigateTo({
      url: '../scoreOrder/scoreOrder',
    })
  },
  /**
   * 前往下单
   */
  toPerfectOrder: function (val) {
    const that = this
    const goodsList = that.data.goodsList
    var good = null
    goodsList.forEach(item => {
      if (item.id === val.currentTarget.dataset.goodsid) {
        good = item
      }
    })
    if (good.balance > 0) {
      if (that.data.score > good.exchangeScores) {
        try {
          let scoreMall = {
            allPrice: good.sellPrice,
            storeId: this.data.storeId,
            goodsList: [],
            orderType: 'scoreMall',
            score: good.exchangeScores
          }
          let tempData = {
            ...good,
            productId: good.id,
            productNum: 1,
            sellPrice: good.sellPrice,
          }
          scoreMall.goodsList.push(tempData)
          console.log(scoreMall)
          wx.setStorageSync('wj_shopcart', scoreMall)
        } catch (e) {
          console.log(e)
        }
        // 判断是否绑定手机号
        wx.navigateTo({
          url: '../perfectOrder/perfectOrder'
        })
      } else {
        wx.showToast({
          title: '积分不足',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      wx.showToast({
        title: '您来晚了，商品已售空',
        icon: 'none',
        duration: 2000
      })
    }
  },
})